from system.object import Object
from system.eventServer import eventServer
from system.gameServer import gameServer
from system.vec2 import Vec2

class Default(Object):
    def __init__(self, parent, type = None, name = None):
        Object.__init__(self, parent, type, name)
        
        self.shudai = self.search("type","shudai.shudai")
        self.units = self.shudai.search("name","units",False)
        self.player = self.shudai.search("name","player",False)
        
        self.menu = self.addChild("gui.menu")
        self.keyMap = self.addChild("system.keyMap")
        
        self.toolbar = self.menu.addChild("defaultToolbar")
        self.fileMenu = self.toolbar.search("name","fileMenu",False)
        self.toolsMenu = self.toolbar.search("name","toolsMenu",False)
        self.sideMenu = self.toolbar.search("name","sideMenu",False)
        
        self.keyMap = self.addChild("system.keyMap")
        self.keyMap.load("defaultKeyMap")
        
        self.camera = self.search("name","camera")
        self.cameraVel = Vec2()
        self.cameraZoom = 0
        self.defaultVar("cameraSpeed",100)
        self.defaultVar("cameraZoomSpeed",0.25)
        
        self.selectedUnit = None
        self.unitMenu = None
        self.stopButton = None
        self.buildMenu = None
        
        self.makePlayerMenu()
        
        eventServer.register("update",self.update)
        
        eventServer.register("pullDownSelect",self.pullDownSelect)
        eventServer.register("buttonClicked",self.buttonClicked)
        eventServer.register("mouseButtonDown",self.mouseButtonDown)
        
        eventServer.register("cameraLeft",self.cameraLeft)
        eventServer.register("cameraRight",self.cameraRight)
        eventServer.register("cameraUp",self.cameraUp)
        eventServer.register("cameraDown",self.cameraDown)
        eventServer.register("cameraIn",self.cameraIn)
        eventServer.register("cameraOut",self.cameraOut)
        
        eventServer.register("changeResource",self.changeResource)
        
    def makePlayerMenu(self):
        self.playerMenu = self.menu.addChild("gui.frame","playerMenu")
        self.playerMenu.setVar("pos",(0.8,0))
        self.playerMenu.setVar("scale",(0.2,0.1))
        
        self.resourceText = {}
        y = 0.5
        step = 0.5 / float(len(self.shudai.getVar("resources")))
        for resource in self.shudai.getVar("resources"):
            text = self.playerMenu.addChild("resourceText")
            text.setVar("renderOp2d","text")
            text.setVar("text","%s: %d" % (resource,self.player.getVar(resource)))
            text.setVar("pos",(0,y))
            y += step
            self.resourceText[resource] = text
            
    def changeResource(self, cmd, args):
        resource = args['resource']
        self.resourceText[resource].setVar("text","%s: %d" % (resource,self.player.getVar(resource)))
        
    def mouseButtonDown(self, cmd, args):
        mouse = Vec2(self.transformMouse(args['x'],args['y']))
        
        for unit in self.units.children.itervalues():
            if (Vec2(unit.getVar("pos")) - mouse).length() < unit.getVar("boundingRadius") * unit.getVar("scale")[0]:
                self.clickUnit(unit,args['button'])
                return
            
        self.clickGround(mouse,args['button'])
        
    def clickUnit(self, unit, button):
        if button == 1 and unit.getVar("side") == self.player.getVar("side"):
            self.selectUnit(unit)
            
        elif button == 3 and self.selectedUnit and self.selectedUnit != unit:
            eventServer.netPull("unitFollow",{'path':self.selectedUnit.getVar("path"),'target':unit.getVar("path")})
            
            if self.selectedUnit.getVar("side") != unit.getVar("side"):
                eventServer.netPull("unitAttack",{'path':self.selectedUnit.getVar("path"),'target':unit.getVar("path")})
            
    def clickGround(self, pos, button):
        
        if button == 1:
            self.unselectUnit()
            
        elif button == 3 and self.selectedUnit:
            eventServer.netPull("unitMoveTo",{'path':self.selectedUnit.getVar("path"),'pos':pos.toTuple()})
        
    def unselectUnit(self):
        if self.selectedUnit:
            self.selectedUnit.removeChild("highlight")
            self.selectedUnit = None
            self.removeUnitMenu()
        
    def selectUnit(self, unit):
        if self.selectedUnit != unit:
            if self.selectedUnit:
                self.selectedUnit.removeChild("highlight")
            
            self.selectedUnit = unit
            
            highlight = self.selectedUnit.addChild("highlight")
            highlight.setVar("renderOp2d","circle")
            highlight.setVar("filled",False)
            s = self.selectedUnit.getVar("boundingRadius")
            highlight.setVar("scale",(s,s))
            
            self.makeUnitMenu(self.selectedUnit)
            
    def removeUnitMenu(self):
        if self.unitMenu:
            self.unitMenu.parent.removeChild(self.unitMenu.getVar("name"))
            self.unitMenu = None
            self.stopButton = None
            self.buildMenu = None
            
    def makeUnitMenu(self, unit):
        self.removeUnitMenu()
        
        self.unitMenu = self.menu.addChild("gui.frame","unitMenu")
        self.unitMenu.setVar("pos",(0.25,0.75))
        self.unitMenu.setVar("scale",(0.5,0.25))
        self.unitMenu.setVar("canClose",True)
        self.unitMenu.setVar("blockPick",True)
        
        nameText = self.unitMenu.addChild("nameText")
        nameText.setVar("renderOp2d","text")
        nameText.setVar("text","name: %s" % unit.getVar("name"))
        nameText.setVar("pos",(0,0.3))
        
        sideText = self.unitMenu.addChild("sideText")
        sideText.setVar("renderOp2d","text")
        sideText.setVar("text","side: %s" % unit.getVar("side"))
        sideText.setVar("pos",(0,0.45))
        
        self.unitMenu.addChildData({"vars":{"text":"Stop"}})
        self.stopButton = self.unitMenu.addChild("gui.button","stopButton")
        self.stopButton.setVar("pos",(0.8,0.8))
        self.stopButton.setVar("scale",(0.2,0.2))
        
        if unit.getVar("buildUnits"):
            self.unitMenu.addChildData({"vars":{"titleText":"Build","options":unit.getVar("buildUnits"),"pos":(0,0.6),"scale":(0.5,0.2)}})
            self.buildMenu = self.unitMenu.addChild("gui.pullDown","buildMenu")
    
    def transformMouse(self, mx, my):
        if self.camera:
            cx,cy = self.camera.getVar("pos")
            csx,csy = self.camera.getVar("scale")
            
            x = (mx - 0.5) * gameServer.screenw * csx + cx
            y = (my - 0.5) * gameServer.screenh * csy + cy
            
            return x,y
            
        else:
            return mx,my
        
    def cameraLeft(self, cmd, args):
        self.cameraVel.x = -args['value'] * self.getVar("cameraSpeed")
        
    def cameraRight(self, cmd, args):
        self.cameraVel.x = args['value'] * self.getVar("cameraSpeed")
        
    def cameraUp(self, cmd, args):
        self.cameraVel.y = -args['value'] * self.getVar("cameraSpeed")
        
    def cameraDown(self, cmd, args):
        self.cameraVel.y = args['value'] * self.getVar("cameraSpeed")
        
    def cameraIn(self, cmd, args):
        self.cameraZoom = args['value'] * self.getVar("cameraZoomSpeed")
        
    def cameraOut(self, cmd, args):
        self.cameraZoom = -args['value'] * self.getVar("cameraZoomSpeed")
        
    def update(self, cmd, args):
        dtime = abs(args['dtime'])
        
        if self.camera:
            self.camera.setVar("pos",(Vec2(self.camera.getVar("pos")) + self.cameraVel * dtime).toTuple())
            dscale = self.cameraZoom * dtime
            self.camera.setVar("scale",(Vec2(self.camera.getVar("scale")) + Vec2(-dscale,-dscale)).toTuple())
        
    def pullDownSelect(self, cmd, args):
        if args['path'] == self.toolsMenu.getVar("path"):
            if args['selection'] == 'editor':
                self.shudai.addChild("shudai.editor","editor")
                
        elif args['path'] == self.fileMenu.getVar("path"):
            if args['selection'] == 'exit':
                gameServer.shutdown = True
                
        elif args['path'] == self.sideMenu.getVar("path"):
            eventServer.pull("setSide",{'side':args['selection']})
            
        elif self.buildMenu and args['path'] == self.buildMenu.getVar("path") and self.selectedUnit:
            eventServer.pull("unitBuild",{"path":self.selectedUnit.getVar("path"),"type":args['selection']})
            
    def buttonClicked(self, cmd, args):
        if self.stopButton and self.stopButton.getVar("path") == args['path'] and self.selectedUnit:
            eventServer.netPull("unitStop",{"path":self.selectedUnit.getVar("path")})
            eventServer.netPull("unitStopWeapons",{"path":self.selectedUnit.getVar("path")})
